<template>
  <div class="jq-table h-full flex-col">
    <SearchForm @handle-reset-form-datas="handleResetFormDatas" :searchForm="searchForm" @handle-search="handleSearch" />
    <div class="page-card h-full" v-loading="loading">
      <JqTable :tableColumn="tableColumn" :tableButtons="tableButtons" :itemsButtons="itemsButtons" :data="tableData"
        :page="page" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" >
        
      <template #status>
          <el-table-column show-overflow-tooltip :min-width="80" prop="visible" label="状态" fit="true" show-header="true"
            align="left">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <!-- <el-switch v-model="scope.row.visible" :active-value="0" :inactive-value="1"
                  @change="setIs('visible', scope.row)" /> -->
                <span :class="scope.row.status === 1 ? 'point1' : 'point2'"></span>
                <span>{{ scope.row.status === 1 ? '启用' :  '停用' }}</span>
              </div>
            </template>
          </el-table-column>
        </template>
      </JqTable>
      <!-- <AddOrUpdate ref="addOrUpdateRef" :dialogDatas="dialogDatas" @sayHello="getList" /> -->
      <AddOrUpdate v-if="showDialog" v-model:dialogVisible="showDialog" ref="addOrUpdateRef" :dialogDatas="dialogDatas"
        @update-list="updateList" />
    </div>
  </div>
</template>

<script lang="ts" setup>
defineOptions({ name: 'SystemMeal' });//套餐管理
interface Row {
  id: number;
  status: number;
}
import { reactive, ref, onMounted, computed } from 'vue';
import { useTable } from '@/hooks/useTable';
import { getMealListFun, reportRequest, MealDetailRequest,mealDeleteRequest,enableOrDisableRequest } from '@/api/system/meal/index';
// import type { IUserItem } from '@/api/user/type';
import { enumListRequest } from '@/api/common';
import { JqTable } from '@/components/Table/index';
import { AddOrUpdate } from './components';
import { useRoute, useRouter } from 'vue-router';
import { useRouteStore } from '@/store';
const routeStore = useRouteStore();
const router = useRouter();
const showDialog = ref(false)
const addOrUpdateRef = ref();
let searchFormParams = reactive({});//查询参数
const currentMenudatas = computed(() => routeStore.currentMenudatas);
let searchForm = reactive([
  {
    type: 'input',
    value: '',
    label: '套餐查询',
    placeholder: '请输入套餐查询',
    eName: 'mealName',
    maxlength:'15',
  },
  {
    type: 'select',
    value: '',
    label: '套餐状态',
    options: () => {
      return mealStatusEnumList;
    },
    eName: 'status'
  }
]);

let dialogAddData = ref({
  //新增数据
  mealName: '',
  points: null,
  remark: '',
  reportIds: [],
  tableData: [],
});

let dialogConfig1 = {
  //查看回显数据
  id: 0,
  mealName: '1',
  points: 0,
  remark: '3',
  reportIds: [],
  tableData: [],
  checkedColumn:[]
};
const tableColumn = reactive([
  { label: '套餐名称', prop: 'mealName', minWidth: '80'  },
  { label: '创建时间', prop: 'createTime', minWidth: '170'  },
  { label: '创建人', prop: 'createBy', minWidth: '80'  },
  { label: '检测项', prop: 'checkItems', minWidth: '80'  },
  { label: '被使用机构数', prop: 'orgCount', minWidth: '140'  },
  { label: '使用点数', prop: 'points', minWidth: '80'  },
  { label: '状态', prop: 'status', minWidth: '80',slot: true  }
]);
let tableButtons = reactive([
  {
    id: 58,
    type: 'primary',
    label: '添加',
    perms: 'sys:pkg:btn:create',
    // onClick: async () => {
    //   await reportFun()
    //   dialogDatas = {
    //     title: '添加套餐',
    //     type: 'add',
    //     datas: dialogAddData.value
    //   };
    //   onAddOrUpdate(dialogDatas);
    // }
    onClick: () => {
      showDialog.value = true
      reportFun()
      dialogDatas = {
        title: '添加套餐',
        type: 'add',
        datas: dialogAddData.value
      };
      // console.log(dialogDatas,"dialogDatasdialogDatas")
      // onAddOrUpdate(dialogDatas);
    }
  }
]);
const onAddOrUpdate = (data?: Recordable) => {
  addOrUpdateRef.value.init(data);
};
let itemsButtons = reactive([
  //来源于数据
  {
    id: 59,
    type: 'primary',
    label: '查看',
    perms: 'sys:pkg:btn:view',
    onClick: async (row: Row) => {
      showDialog.value = true
      // await getMealDetailFun(row,'check')
      dialogDatas = {
        title: '查看套餐',
        type: 'check',
        datas: row
      };
      // onAddOrUpdate(dialogDatas);
    }
  },
  {
    id: 60,
    type: 'primary',
    label: '编辑',
    perms: 'sys:pkg:btn:edit',
    onClick: async (row: Row) => {
      showDialog.value = true
      // await getMealDetailFun(row,'edit')
      dialogDatas = {
        title: '编辑',
        type: 'edit',
        datas: row
      };
      // onAddOrUpdate(dialogDatas);
    }
  },
  // {
  //   eName: 'stop',
  //   id: 61,
  //   type: 'warning',
  //   label: '停用',
  //   onClick: (row: any,) => {
  //     enableOrDisableRequest({ id: row.id, status: row.status === 1 ? 2 : 1 }).then(res=> {
  //       getList();
  //       ElMessage.success('修改成功')
  //     })
  //   }
  // },
  {
    id: 61,
    eName: 'pause',
    perms: 'sys:pkg:btn:status',
    statusConfig:{
        1:'启用',
        2:'停用',
        // 3:'待激活'
      },
    onClick: async (row: any) => {
      enableOrDisableRequest({ id: row.id, status: row.status === 1 ? 2 : 1 }).then(res=> {
        getList();
        ElMessage.success('修改成功')
      })
    }
  },
  {
    id: 62,
    type: 'danger',
    perms: 'sys:pkg:btn:del',
    label: '删除',
    onClick: (row) => {
      deleteFun(row)
    }
  }
]);
let dialogDatas = reactive({});
const { tableData, page, loading, resetParams, getList, handleCurrentChange, handleSizeChange } =
  useTable({
    apiFn: getMealListFun,
    params: ()=>searchFormParams
  });
// 套餐状态下拉
let mealStatusEnumList = reactive([])
const getMealStatusEnum = async () => {
  const data: any = await enumListRequest({ enumName: 'MealStatusEnum' });
  mealStatusEnumList = data.data;
};
const tableButtonsPermission = (datas: any[], datas1: any[]) => {
  return datas.filter(function (item1: { perms: string }) {
    return datas1.find(function (item2: { perms: string }) {
      return item1.perms === item2.perms;
    });
  });
};
// 获取检测项列表
const reportFun = async () => {
  let data: any = await reportRequest({})
  let res = data.data
  dialogAddData.value.tableData = res
  console.log(res, '获取检测项列表');
}
// 获取套餐详情
const getMealDetailFun = async (params: any,type) => {
  const data: any = await MealDetailRequest({ mealId: params.id })
  let res = data.data;
  let newArray = []
  if (type ==='edit') {
    newArray = res.reportProjectResps;
    dialogConfig1.checkedColumn = (res.reportProjectResps).filter((obj:any) => obj.isCheck === true);//选中的
  } else {
    newArray = (res.reportProjectResps).filter((obj:any) => obj.isCheck === true);
  }
  dialogConfig1.id = res.id;
  dialogConfig1.mealName = res.mealName;
  dialogConfig1.points = res.points;
  dialogConfig1.remark = res.remark;
  dialogConfig1.reportIds = res?.reportIds;
  dialogConfig1.tableData = newArray;   //区分查看和编辑
}
// 删除
const deleteFun = (rowData: any) => {
  ElMessageBox.confirm('是否删除？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const data: any = await mealDeleteRequest([rowData.id]);
      if (data.code === 2000) {
        ElMessage.success('删除成功')
        getList();
      } else {
        ElMessage.error(data?.message)
        return
      }
      return
    })
    // .catch(() => {
    //   ElMessage({
    //     type: 'info',
    //     message: '取消操作'
    //   });
    // });
};
/* 高级搜索重置 */
const handleResetFormDatas = () => {
  searchFormParams={}
  searchForm = searchForm.map((item) => {
    if (item.value) {
      item.value = '';
    }
    return item;
  });
 getList();
};
const updateList = () => {
  getList();
  showDialog.value = false
}
onMounted(() => {
  if(!currentMenudatas.value) {
    return
  }
  tableButtons = tableButtonsPermission(tableButtons, currentMenudatas.value.tableButtons); //tableButtons根据数据返回按钮信息控制权限
  itemsButtons = tableButtonsPermission(itemsButtons, currentMenudatas.value.itemsButtons); //itemButtons根据数据返回按钮信息控制权限
  console.log(itemsButtons);
  
});
// 数据筛选
const handleSearch = async (searchFormParamsDatats: {}) => {
  Object.assign(searchFormParams, searchFormParamsDatats);
  await getList();
};
getMealStatusEnum()
</script>
<style scoped></style>
